# name : proc means(autoname)+tranpose (character) for one var
# key : proc.means.autoname.transpose.character.one.var
# contributor: Shuguang Sun
# --
/* Request statistics on the OUTPUT statement. */
/* Use the AUTONAME option to create variable names in the form: */
/* variable_statistic */
%let varname=${3:var};
proc means data=${1:din} noprint;
  format ${2:group} $ogroup.;
  class $2 / order = formatted;
  var &varname.;
  by ${4:avisit};
  output out = ${5:_out1} n= mean= std= median= q1= q3= min= max=/ autoname;
  where ;
run;

/* total */
data $5 (drop=_type_ _freq_
  &varname._n &varname._mean &varname._stddev &varname._median
  &varname._q1 &varname._q3 &varname._min &varname._max);
  set $5;
  if _type_ eq 0 then $2 = "Total";
  &varname._n_      = put(&varname._n, 18.-l);
  &varname._msd_    = strip(put(&varname._mean, 18.2)) || " (" || strip(put(&varname._stddev, 18.2)) || ")";
  &varname._median_ = put(&varname._median, 18.2-l);
  &varname._q13_    = strip(put(&varname._q1, 18.2)) || " - " || strip(put(&varname._q3, 18.2));
  &varname._range_  = strip(put(&varname._min, 18.2)) || " - " || strip(put(&varname._max, 18.2));
run;

/* Transpose the data set so that each statistic becomes an observation. */
proc transpose data=$5 out=${6:_out2} (where = (_name_ eq: "&varname._")) prefix=a_;
  format ${2:group} $group.;
  var _character_;
  id $2;
  by $4;
run;

/* Create new variables that contain the statistic name and the */
/* original variable name. */
data ${7:dout};
  set $6;
  length varname $8;
  lenvar=length(_name_);
  lenstat=index(reverse(trim(_name_)),'_') - 1;
  /*
   * varname=substr(_name_,1,(lenvar-lenstat)-1);
   * stat=scan(_name_,-1,'_');
   */
  varname = scan(_name_,1,'_');
  stat = scan(_name_,2,'_');
  drop _name_ lenvar lenstat;
run;

proc sort data=$7;
  by varname $4;
run;

proc print data=$7 noobs;
  var varname $4 stat a_:;
  title "$0";
run;
